package com.hyjx.framework.component.mutidatasource;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

import java.io.IOException;

/**
 * 动态数据源bean
 */
public class DynamicCreateDataSourceBean implements ApplicationContextAware, ApplicationListener {
    
    @Override
    public void onApplicationEvent(ApplicationEvent arg0) {
        // TODO Auto-generated method stub
        
    }
    
    @Override
    public void setApplicationContext(ApplicationContext arg0)
            throws BeansException {
        // TODO Auto-generated method stub
        
    }/*
    private ConfigurableApplicationContext app;  
    private JdbcTemplate jdbcTemplate;  
      
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate)  
    {  
        this.jdbcTemplate = jdbcTemplate;  
    }  
  
    private DynamicDataSource dynamicDataSource;  
      
    public void setDynamicDataSource(DynamicDataSource dynamicDataSource) {  
        this.dynamicDataSource = dynamicDataSource;  
    }  
  
    public void setApplicationContext(ApplicationContext app) throws BeansException {  
        this.app = (ConfigurableApplicationContext)app;  
    }  
  
      
    public void onApplicationEvent(ApplicationEvent event) {  
        // 如果是容器刷新事件OR Start Event  
        if (event instanceof ContextRefreshedEvent) {  
            try {  
                regDynamicBean();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            //System.out.println(event.getClass().getSimpleName()+" 事件已发生！");  
        }  
          
    }  
  
    private void regDynamicBean() throws IOException {  
        // 解析属性文件，得到数据源Map  
        Map<String, Object> mapCustom = parsePropertiesFile();
        BasicDataSource baseds=(BasicDataSource) SpringBeanUtil.getBean("dataSourceS");
		BasicDataSource interfaceds=(BasicDataSource) SpringBeanUtil.getBean("dataSourceS");
		mapCustom.put("dataSourceS", baseds);
		mapCustom.put("dataSourceInterface", interfaceds);
        // 把数据源bean注册到容器中  
        addSourceBeanToApp(mapCustom);  
    }  
  
    *//**
     * 功能说明：根据DataSource创建bean并注册到容器中 
     *
     * @param acf
     * @param mapCustom
     *//*  
    private void addSourceBeanToApp(Map<String, Object> mapCustom) {  
        DefaultListableBeanFactory acf = (DefaultListableBeanFactory) app  
                .getAutowireCapableBeanFactory();  
  
        String DATASOURCE_BEAN_CLASS = "org.apache.commons.dbcp.BasicDataSource";  
        BeanDefinitionBuilder bdb;  
          
        Iterator<String> iter = mapCustom.keySet().iterator();  
          
        Map<Object, Object> targetDataSources = new LinkedHashMap<Object, Object>();  
          
       // baseBeanComm = new ChildBeanDefinition("dataSource");  
        //  将默认数据源放入 targetDataSources map中  
  
        // 根据数据源得到数据，动态创建数据源bean 并将bean注册到applicationContext中去  
        while (iter.hasNext()) {  
            //  bean ID  
            String beanKey = iter.next();
            BasicDataSource ds=(BasicDataSource) mapCustom.get(beanKey);
            String driverClassName=ds.getDriverClassName();
            String url=ds.getUrl();
            String username=ds.getUsername();
            String password=ds.getPassword();
            
            //  创建bean  
            bdb = BeanDefinitionBuilder.rootBeanDefinition(DATASOURCE_BEAN_CLASS);  
            bdb.getBeanDefinition().setAttribute("id", beanKey);  
            //bdb.addPropertyValue("driverClassName", "org.gjt.mm.mysql.Driver");
            bdb.addPropertyValue("driverClassName", driverClassName); 
            bdb.addPropertyValue("url", url);  
            bdb.addPropertyValue("username", username);  
            bdb.addPropertyValue("password", password);  
            bdb.addPropertyValue("timeBetweenEvictionRunsMillis", 3600000);  
            bdb.addPropertyValue("minEvictableIdleTimeMillis", 3600000);  
            //  注册bean  
            acf.registerBeanDefinition(beanKey, bdb.getBeanDefinition());  
              
            //  放入map中，注意一定是刚才创建bean对象  
            targetDataSources.put(beanKey, app.getBean(beanKey));  
              
        }  
        //  将创建的map对象set到 targetDataSources；  
        dynamicDataSource.setTargetDataSources(targetDataSources);  
          
        //  必须执行此操作，才会重新初始化AbstractRoutingDataSource 中的 resolvedDataSources，也只有这样，动态切换才会起效  
        dynamicDataSource.afterPropertiesSet();  
    }  
  
    *//**
     * 功能说明：GET ALL SM_STATIONS FROM DB1 
     *
     * @return
     * @throws IOException
     *//*  
    private Map<String, Object> parsePropertiesFile()  
            throws IOException {  
    	IBaseDao dao =  (IBaseDao)SpringBeanUtil.getBean("baseDao");
    	List<DataSourceInfo> dsList = dao.queryObjectList("multidatasource.getAllDataSource", null);
        Iterator iterator = dsList.iterator();  
        
        Map<String, Object> mds = new HashMap<String, Object>();  
        while (iterator.hasNext()) {  
            DataSourceInfo dsi  = (DataSourceInfo) iterator.next();    
            String key=dsi.getDatasourcename();
            if(key!=null){
            	mds.put(key, dsi);
            }
        }  
        return mds;  
    }  
*/
}
